package com.wwtech.epp.ui.activity.mine;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStructure;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ninjia.ninjiabaselibrary.utils.SpUtil;
import com.socks.library.KLog;
import com.suke.widget.SwitchButton;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.ui.activity.mine.component.DaggerNewMessageInformComponent;
import com.wwtech.epp.ui.activity.mine.contract.NewMessageInformContract;
import com.wwtech.epp.ui.activity.mine.module.NewMessageInformModule;
import com.wwtech.epp.ui.activity.mine.presenter.NewMessageInformPresenter;
import com.wwtech.epp.utils.DateUtils;
import com.wwtech.epp.utils.ToastUtil;
import com.wwtech.epp.view.RxDialogWheelDayMinute;

import java.util.Date;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

import static com.wwtech.epp.contain.ContainValue.endTime;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.mine
 * @Description: $description
 * @date 2017/09/04 11:52:10
 */

public class NewMessageInformActivity extends BaseActivity implements NewMessageInformContract.View {

    @Inject
    NewMessageInformPresenter mPresenter;
    @BindView(R.id.account)
    TextView account;
    /**
     * 消息提醒
     */
    @BindView(R.id.sb_im_message)
    SwitchButton sbImMessage;

    @BindView(R.id.no_disturbing)
    TextView noDisturbing;

    /**
     * 免打扰时段
     */
    @BindView(R.id.sb_no_dispater)
    SwitchButton sbNoDispater;

    @BindView(R.id.ll_no_dispater)
    LinearLayout llNoDispater;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ll_no_sb_dispater)
    LinearLayout llNoSbDispater;
    private RxDialogWheelDayMinute mRxDialogWheelYearMonthDay;

    private String mTimeFormat = "HH:mm:ss";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_new_message_inform);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("新消息通知");
        sbNoDispater.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    SpUtil.putBoolean(NewMessageInformActivity.this, ContainValue.appChatInform, true);
                    llNoDispater.setVisibility(View.VISIBLE);
                    //打开免打扰
                    String startTime = SpUtil.getString(NewMessageInformActivity.this, ContainValue.startTime, "23:00:00");
                    String endTime = SpUtil.getString(NewMessageInformActivity.this, ContainValue.endTime, "07:00:00");
                    tvStartTime.setText(startTime);
                    tvEndTime.setText(endTime);
                    Date dataStart = DateUtils.stringToDate(startTime, mTimeFormat);
                    Date dataEnd = DateUtils.stringToDate(endTime, mTimeFormat);
                    long spansTime = DateUtils.compareMin(dataStart, dataEnd);
                    setConversationTime(startTime, (int) spansTime);
                } else {
                    //关闭免打扰
                    SpUtil.putBoolean(NewMessageInformActivity.this, ContainValue.appChatInform, false);
                    llNoDispater.setVisibility(View.GONE);
                    RongIM.getInstance().setNotificationQuietHours("00:00:00", 1, new RongIMClient.OperationCallback() {
                        @Override
                        public void onSuccess() {
                            KLog.i("移除免打扰成功");
                            SpUtil.putBoolean(NewMessageInformActivity.this, ContainValue.isOpenDisturb, false);
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });
                }
            }
        });
        sbImMessage.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    if (sbNoDispater.isChecked()) {
                        llNoDispater.setVisibility(View.VISIBLE);
                    }
                    llNoSbDispater.setVisibility(View.VISIBLE);
                    RongIM.getInstance().removeNotificationQuietHours(new RongIMClient.OperationCallback() {
                        @Override
                        public void onSuccess() {
                            KLog.i("移除免打扰");
                            SpUtil.putBoolean(NewMessageInformActivity.this, ContainValue.isOpenDisturb, true);
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });

                } else {
                    //sbNoDispater.setChecked(false);
                    llNoDispater.setVisibility(View.GONE);
                    llNoSbDispater.setVisibility(View.GONE);
                    RongIM.getInstance().setNotificationQuietHours("00:00:00", 1439, new RongIMClient.OperationCallback() {
                        @Override
                        public void onSuccess() {
                            KLog.i("设置全天免打扰成功");
                            SpUtil.putBoolean(NewMessageInformActivity.this, ContainValue.isOpenDisturb, false);
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });
                }
            }
        });
    }

    @Override
    protected void initData() {
        if (SpUtil.getBoolean(this, ContainValue.appChatInform, false)) {
            sbNoDispater.setChecked(true);
        } else {
            sbNoDispater.setChecked(false);
            llNoDispater.setVisibility(View.GONE);
        }
        tvStartTime.setText(SpUtil.getString(this, ContainValue.startTime, "23:00:00"));
        tvEndTime.setText(SpUtil.getString(this, endTime, "07:00:00"));
        if (SpUtil.getBoolean(this, ContainValue.isOpenDisturb, true)) {
            sbImMessage.setChecked(true);
        } else {
            sbImMessage.setChecked(false);
            llNoSbDispater.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setupActivityComponent() {
        DaggerNewMessageInformComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .newMessageInformModule(new NewMessageInformModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(NewMessageInformContract.NewMessageInformContractPresenter presenter) {
        mPresenter = (NewMessageInformPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    private void initWheelYearMonthDayDialog(int flag) {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelDayMinute(this, 1994, 2017);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        if (flag == 0) {
                            tvStartTime.setText(mRxDialogWheelYearMonthDay.getSelectorMonth() + ":" + mRxDialogWheelYearMonthDay.getSelectorDay() + ":00");
                            SpUtil.putString(NewMessageInformActivity.this, ContainValue.startTime, tvStartTime.getText().toString());
                            Date dataStart = DateUtils.stringToDate(tvStartTime.getText().toString(), mTimeFormat);
                            String endTime = SpUtil.getString(NewMessageInformActivity.this, ContainValue.endTime, "07:00:00");
                            Date dataEnd = DateUtils.stringToDate(endTime, mTimeFormat);
                            long spansTime = DateUtils.compareMin(dataStart, dataEnd);
                            setConversationTime(tvStartTime.getText().toString(), (int) Math.abs(spansTime));
                        } else {
                            tvEndTime.setText(mRxDialogWheelYearMonthDay.getSelectorMonth() + ":" + mRxDialogWheelYearMonthDay.getSelectorDay() + ":00");
                            SpUtil.putString(NewMessageInformActivity.this, endTime, tvEndTime.getText().toString());
                            Date dataEnd = DateUtils.stringToDate(tvEndTime.getText().toString(), mTimeFormat);
                            String startTime = SpUtil.getString(NewMessageInformActivity.this, ContainValue.startTime, "23:00:00");
                            Date dataStart = DateUtils.stringToDate(startTime, mTimeFormat);
                            long spansTime = DateUtils.compareMin(dataStart, dataEnd);
                            setConversationTime(startTime, (int) Math.abs(spansTime));
                        }
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.show();
        // ------------------------------------------------------------------选择日期结束
    }

    @OnClick({R.id.tv_start_time, R.id.tv_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                initWheelYearMonthDayDialog(0);
                break;
            case R.id.tv_end_time:
                initWheelYearMonthDayDialog(1);
                break;
        }
    }

    /**
     * 设置勿扰时间
     *
     * @param startTime 设置勿扰开始时间 格式为：HH:mm:ss
     * @param spanMins  0 < 间隔时间 < 1440
     */
    private void setConversationTime(final String startTime, final int spanMins) {

        if (!TextUtils.isEmpty(startTime)) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    if (spanMins > 0 && spanMins < 1440) {
                        KLog.i("", "----设置勿扰时间startTime；" + startTime + "---spanMins:" + spanMins);

                        RongIM.getInstance().setNotificationQuietHours(startTime, spanMins, new RongIMClient.OperationCallback() {

                            @Override
                            public void onSuccess() {
                                KLog.i("设置免打扰成功。");
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {
                                KLog.e("----yb----设置会话通知周期-oonError:" + errorCode.getValue());
                            }
                        });
                    } else {
                        getWindow().getDecorView().post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.displayShortToast("间隔时间必须>0");
                            }
                        });
                    }
                }
            });
        }
    }

    /**
     * 得到"HH:mm:ss"类型时间
     *
     * @param hourOfDay 小时
     * @param minite    分钟
     * @return "HH:mm:ss"类型时间
     */
    private String getDaysTime(final int hourOfDay, final int minite) {
        String daysTime;
        String hourOfDayString = "0" + hourOfDay;
        String minuteString = "0" + minite;
        if (hourOfDay < 10 && minite >= 10) {
            daysTime = hourOfDayString + ":" + minite + ":00";
        } else if (minite < 10 && hourOfDay >= 10) {
            daysTime = hourOfDay + ":" + minuteString + ":00";
        } else if (hourOfDay < 10 && minite < 10) {
            daysTime = hourOfDayString + ":" + minuteString + ":00";
        } else {
            daysTime = hourOfDay + ":" + minite + ":00";
        }
        return daysTime;
    }
}